<?php
class Usuario_model extends CI_Model {
	public $nombre;
	public $id;
	public $apellido;
	public $rendimiento;
	public $equipo;
	public $table = 'usuario';
	public $pass;
	public $email;
	public $username;
	public $rol;
	public $fecha;
	public $imagen;
	function __construct() {
		$this->load->model ( 'Rol_model' );
	}
	public function guardar($user) {
		$this->db->insert ( $this->table, $user );
		return $this->db->insert_id ();
	}
	public function get_usuario_by_id($id) {
		return $this->obtener_usuario ( 'id', $id );
	}
	public function get_usuario_by_email($email) {
		return $this->obtener_usuario ( 'email', $email );
	}
	public function login($email, $pass) {
		$this->db->from ( $this->table )->where ( 'email', $email )->where ( 'pass', $pass );
		$user = $this->db->get ();
		if ($user->num_rows () > 0) {
			$user = $user->row ( 0, 'Usuario_model' );
			$user->rol = $this->Rol_model->get_rol_by_id ( $user->rol_id );
			
			return $user;
		} else
			return null;
	}
	public function existe_el_correo($email) {
		$this->db->select ( 'email' )->from ( $this->table )->where ( 'email', $email );
		$consulta = $this->db->get ();
		return ($consulta->num_rows () > 0);
	}
	public function existe_el_username($username) {
		$this->db->select ( 'username' )->from ( $this->table )->where ( 'username', $username );
		$consulta = $this->db->get ();
		return ($consulta->num_rows () > 0);
	}
	private function obtener_usuario($atributo, $valor) {
		$this->db->from ( $this->table );
		$this->db->where ( $atributo, $valor );
		$consulta = $this->db->get ();		
		if ($consulta->num_rows () > 0) {
			$usuario = $consulta->row ( 0, 'Usuario_model' );
			$usuario->rol = $this->Rol_model->get_rol_by_id ( $usuario->rol_id );
			return $usuario;
		} else
			return null;
	}
	private function get_rol_name() {
		return $this->rol->get_name ();
	}
	public function actualizar($user_id, $array) {
		$this->db->where ( 'id', $user_id );
		$this->db->update ( $this->table, $array );
	}
	public function subir_imagen($user_id, $imagen) {
		$this->db->where ( 'id', $user_id );
		$this->db->update ( $this->table, $imagen );
	}
	public function es_admin() {
		return strcmp ( $this->get_rol_name (), Roles::$ADMIN ) === 0;
	}
}
?>